Ext.define('AmpleHarvest.views.gsbrowse.browse',
{
	extend			: 'Ext.panel.Panel',
	alias			: 'widget.ampleharvest-views-gsbrowse-browse',
	requires		:
	[
			"AmpleHarvest.objects.category.checkList"
	],
//	title			: 'Categories',
	width			: 300,
	border			: 0,
	collapsible		: false,
	idPrefix		: 'gsbrowse',
	resizable		: false,
	queryStorage	: [],
	layout			: 'accordion',
//	iconCls			: 'toolbar-article-enhancement', // TODO: check for best icon to use
	listeners		:
	{
		// TODO: create a getResults event that takes all checked items and processes the request for the results window
		
		dataResponse	: function(object)
		{
			if(object.ajaxProperties.config.preload)
			{
				console.log('preload response');
				console.log(object);
			}
			object = this.removeEmptyCategory(object);
			// TODO: See if converting to bubble events would work better
			// TODO: Hanlde multi-select 
			var m_obj_browse = Ext.create("AmpleHarvest.objects.category.checkList",
					{
						AHcaller		: this,
						id				: this.idPrefix+object.ajaxProperties.config.title,
						alias			: 'widget:'+this.idPrefix+object.ajaxProperties.config.title,
						title			: object.ajaxProperties.config.title,
						myUrl			: object.ajaxProperties.url,
						selectedItems	: [],
						level			: object.ajaxProperties.config.level,
						store 			: Ext.create('AmpleHarvest.DATA.Store.gsbrowse.appCategory',
										{
											data			: object,
											proxy			: {
												      type				: 'memory',
												      reader         	:
												      {
												         type        	: 'json',
												         root        	: 'collection',
												         totalProperty  : 'totalCount'
												      }
												   }
										})
							});
			m_obj_browse.getStore().load();
			this.add(m_obj_browse);
        	this.fireEvent('buildQuery');
		},
		
		autoResponse	: function(obj)
		{
			console.log('auto response');
			console.log(obj);
		},
		
		autoPopulate	: function(obj_query)
		{
			console.log('ONLY ONE TIME FOR THIS');
			for(var a in obj_query)
			{
				for(var b in obj_query[a])
				{
					console.log(b);
					var obj_item = Ext.ComponentMgr.get(b);
					
					console.log(obj_query[a][b]);

					for(var c in obj_query[a][b]){}
					{
						console.log(c);
						var id = obj_item.getStore().find('name', obj_query[a][b][c].name);
						console.log('DO THIS ONCE'+id);
//						obj_item.fireEvent('processingStart');
						
//						obj_item.getSelectionModel().select(id, true, true);
			        	
						obj_item.add_checklist(obj_query[a][b][c].name, this, true);
						
					}
				}
			}
			
		}
	},
	
	loadBoxes	: function(str_id)
	{
		console.log(str_id);
	},
	
	checkBoxes	: function(str_id, arr_items)
	{
		console.log(str_id);
		console.log(arr_items);
	},
	
	initComponent	: function()
	{
		this.loadMask = new Ext.LoadMask(this, {msg:"Please wait..."});
		
		this.queryStorage = [];
		this.m_obj_util = Ext.create('AmpleHarvest.util.utility');
		this.m_obj_util.AHcaller	= this;
		this.m_obj_util.bool_destory= false;
		this.m_obj_util.verifyData = function(obj_data)
      	{
			if(Ext.isArray(obj_data.collection))
			{
				if(obj_data.totalCount > 1)
				{
					return true;
				}
			}
			return false;
      	};
      	this.m_obj_util.getData('/solr-gs-base/app/category/',{},{test:'json'},'GET', { title : 'Category', level : '/category/'}, {});
		
		// TODO: Discuss the best way to handle the blank category

		this.callParent();
	},
	
	verifyData	: function(obj_data)
  	{
		if(Ext.isArray(obj_data.collection))
		{
			if(obj_data.totalCount > 1)
			{
				return true;
			}
		}
		return false;
	},
	
	createSelectionObject	: function(str_id, str_name, str_parent_name, str_level)
	{
		var level = this.convertLevelString(str_level);
		var storage = this.findStorageLocation(this.queryStorage, str_id, str_parent_name);
		var rootObject = new Object();
		var obj_values = new Object();
		obj_values.name = str_name;
		obj_values.leaf = true;		
		obj_values.level = level;
		
		if(!Ext.isArray(storage))
		{
			storage = this.queryStorage;
			var arr_content	= new Array();
			rootObject[str_id] = arr_content;
			rootObject[str_id].push(obj_values);
		} else {
			rootObject = obj_values
		}
		storage.push(rootObject);
//		console.log(this.queryStorage);
		this.ownerCt.fireEvent('processQuery', this.queryStorage);
	},
	
	removeFromSelectionObject	: function(id, name)
	{
		this.findRecordToRemove(this.queryStorage, id, name);
		this.ownerCt.fireEvent('processQuery', this.queryStorage);
	},
	
	findRecordToRemove	: function(obj, id, name)
	{
		for(var a in obj)
		{
			for(var b in obj[a])
			{
				for(var c in obj[a][b])
				{
					if(obj[a][b][c]['name'] == name && b == id)
					{
						obj[a][b].splice(c, 1);
						if(obj[a][b].length < 1)
						{
							return 'empty';
						}
						return 'full';
					} 
					else if (obj[a][b][c]['leaf'] == false)
					{
						var results = this.findRecordToRemove(obj[a][b][c]['children'], id, name);
						if(results == 'empty')
						{
							obj[a][b][c]['leaf'] = true;
							delete obj[a][b][c]['children'];
						}
					}
				}
			}
		}
	},
	
	findStorageLocation	:  function(obj, id, parent)
	{
		// TODO: need to test out nesting a bit more. I think i had issue with Window 3 deep not nesting
		// TODO: seem to be having a timing issue with the passed query
		
		for(var a in obj)
		{
			for(var b in obj[a])
			{
				if(id == b)
				{
					return obj[a][b];
				}
				for (var c in obj[a][b])
				{
					if(obj[a][b][c].name == parent)
					{
						if(obj[a][b][c].leaf)
						{
							obj[a][b][c].leaf = false;
							obj[a][b][c].children = new Array();
							var obj_push = new Object();
							obj_push[id] = new Array();
							obj[a][b][c].children.push(obj_push);
							return obj_push[id];
						} else {
							//var obj_return = obj[index][prop][item]['children'];
							for (var d in obj[a][b][c]['children'])
							{
								if(obj[a][b][c]['children'][d][id])
								{
									return obj[a][b][c]['children'][d][id];
								}
							}
						}
					}
					if(obj[a][b][c].leaf == false)
					{
						return this.findStorageLocation(obj[a][b][c].children, id, parent);
					}
				}	
			}
		}
		return false;
	},
	
	convertLevelString : function(key)
	{
		var arr_levels = new Array();
		arr_levels['/category/'] = 'appCategory';
		arr_levels['/subcategory/'] = 'appSubCategory';
		arr_levels['/subsubcategory/'] = 'appSubSubCategory';
		return arr_levels[key];
	},
	
	removeEmptyCategory : function(object)
	{
		for(var x in object['collection'])
		{
			if(object['collection'][x]['name'] == '')
			{
				object['collection'].splice(x, 1);
				break;
			}
		}
		return object;
	}
}
);
